﻿using System.Diagnostics;
using Xabe.FFmpeg;

namespace wav2mp4;

public class convertToMp4
{
    public async void convert()
    {
        // 设置FFmpeg的可执行文件路径
        FFmpeg.SetExecutablesPath(@"C:\Users\crown\Downloads\ffmpeg-master-latest-win64-gpl\bin");

        string inputFolderPath = @"C:\Users\crown\Downloads\input"; // 输入文件夹路径
        string outputFolderPath = @"C:\Users\crown\Downloads\output"; // 输出文件夹路径
        string inputImagePath = @"C:\Users\crown\Downloads\img\fo.jpg"; // 图片文件路径
        
        // 获取输入文件夹中的所有WAV文件
        var wavFiles = Directory.GetFiles(inputFolderPath, "*.wav");

        foreach (var wavFilePath in wavFiles)
        {
            // 获取不带扩展名的文件名
            var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(wavFilePath);

            // 构建SRT文件路径
            var srtFilePath = Path.Combine(inputFolderPath, $"{fileNameWithoutExtension}.srt");
            Console.WriteLine(srtFilePath);
            // 检查SRT文件是否存在
            if (!File.Exists(srtFilePath))
            {
                Console.WriteLine($"No matching SRT file found for {wavFilePath}");
                continue;
            }

            // 构建输出MP4文件路径
            var outputVideoPath = Path.Combine(outputFolderPath, $"{fileNameWithoutExtension}.mp4");

            try
            {
                // 调用转换方法
                await ConvertToMp4(inputImagePath, wavFilePath, srtFilePath, outputVideoPath);
                Console.WriteLine($"Successfully converted: {outputVideoPath}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error converting {wavFilePath}: {e.Message}");
            }
        }
        Console.WriteLine("完成");
    }
    
    private static async Task ConvertToMp4(string imagePath, string audioPath, string subtitlePath, string outputPath)
    {
        String ffmpegCommand=$" -loop 1 -i \"{imagePath}\" -i \"{audioPath}\" -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest:original_size=1920x1080 \"{outputPath}\"";
        Console.WriteLine(ffmpegCommand);
        // 启动FFmpeg进程
        Process ffmpegProcess = new Process();
        ffmpegProcess.StartInfo.FileName = "ffmpeg.exe";
        ffmpegProcess.StartInfo.Arguments = ffmpegCommand;
        ffmpegProcess.StartInfo.UseShellExecute = false;
        ffmpegProcess.StartInfo.RedirectStandardOutput = true;
        ffmpegProcess.StartInfo.RedirectStandardError = true;
        ffmpegProcess.StartInfo.CreateNoWindow = true;

        ffmpegProcess.Start();

        // 读取输出（或者错误输出）
        string output = ffmpegProcess.StandardError.ReadToEnd();

        ffmpegProcess.WaitForExit();

        if (ffmpegProcess.ExitCode == 0)
        {
            Console.WriteLine($"成功生成视频：{outputPath}");
        }
        else
        {
            Console.WriteLine($"生成视频失败：{outputPath}");
            Console.WriteLine($"错误信息：{output}");
        }
    }
}
